package com.wzw.shoppingcart.service.impl;

import com.wzw.shoppingcart.entity.CartLine;
import com.wzw.shoppingcart.entity.Discount;
import com.wzw.shoppingcart.entity.Product;
import com.wzw.shoppingcart.service.DiscountPromotionService;
import com.wzw.shoppingcart.service.DiscountService;
import com.wzw.shoppingcart.service.PromotionService;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

import static com.wzw.shoppingcart.constant.Constant.ANOTHER_DISCOUNT;

/**
 *@author wzw
 * 2023/4/16
 */
@Slf4j
@Service
@Setter(onMethod_ = {@Autowired})
public class AnotherDiscountServiceImpl implements DiscountPromotionService {
    private PromotionService promotionService;
    private DiscountService discountService;

    @Override
    public BigDecimal calculateDiscount(List<CartLine> cartLines, BigDecimal totalOriginPrice) {

        List<Product> productList = promotionService.promotionProduct(cartLines, ANOTHER_DISCOUNT);

        Discount discount = discountService.getByType(ANOTHER_DISCOUNT);
        BigDecimal discountRate = discount.getDiscountRate();
        Integer conditionAmount = discount.getConditionAmount();

        if (productList.size() < conditionAmount) {
            discountService.setProductDiscountPrice(cartLines, productList, BigDecimal.ONE);
            return BigDecimal.ZERO;
        }

        Integer minCount = getMinCountCartLine(productList, cartLines).getProductCount();

        BigDecimal totalUnitPrice = productList.stream()
                .map(Product::getPrice)
                .reduce(BigDecimal.ZERO, BigDecimal::add);


      return totalUnitPrice.multiply(new BigDecimal(minCount)).
                multiply(BigDecimal.ONE.subtract(discountRate));

    }


    public CartLine getMinCountCartLine(List<Product> productList, List<CartLine> cartLines) {
        List<Integer> productIds = productList.stream()
                .map(Product::getProductId)
                .collect(Collectors.toList());
        List<CartLine> cartLineList = cartLines.stream()
                .filter(c -> productIds.contains(c.getProductId()))
                .collect(Collectors.toList());
        return cartLineList.stream()
                .min(Comparator.comparingInt(CartLine::getProductCount))
                .orElseThrow(()-> new RuntimeException("不存在最小数量"));

    }
}
